using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using Ninject.Core;
using TaoSharp.Core;
using TaoSharp.Core.Domain;

namespace TaoWeb.Controllers
{
    public class AssembliesController : Controller
    {
        private const string AdministratorRole = "administrator";

        [Inject]
        public DataRepository Repository;

        [Inject]
        public EntryPoint EntryPoint;
        //
        // GET: /Assemblies/

        public ActionResult Index()
        {
            return View(Repository.SelectAll<AssemblyItem>());
        }

        public ActionResult Details(int? id)
        {
            // TODO: do something if Id is null
            AssemblyItem assemblyItem = Repository.Select<AssemblyItem>(id.Value);
            return View(assemblyItem);
        }

        public ActionResult Create()
        {
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post), Authorize(Order = 0, Roles = AdministratorRole)]
        public ActionResult Create(FormCollection formCollection)
        {
            try
            {
                // save file
                foreach (string file in Request.Files)
                {
                    HttpPostedFileBase postedFile = Request.Files[file];
                    if (postedFile != null)
                    {
                        string basePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Content\Assemblies");
                        string savedFilename = Path.Combine(basePath, Path.GetFileName(postedFile.FileName));

                        postedFile.SaveAs(savedFilename);
                        EntryPoint.ProcessAssembly(savedFilename);
                    }
                }

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}